package com.bianqian.demo.interceptor;

import com.bianqian.demo.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    
    private final JwtUtil jwtUtil;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        
        String token = request.getHeader("Authorization");
        
        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("请求缺少Authorization头或格式不正确");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未提供有效的token\",\"data\":null}");
            return false;
        }
        
        token = token.substring(7); // 移除"Bearer "前缀
        
        if (!jwtUtil.validateToken(token)) {
            log.warn("token验证失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token已过期或无效\",\"data\":null}");
            return false;
        }
        
        // 将用户ID添加到请求属性中，供后续使用
        Long userId = jwtUtil.getUserIdFromToken(token);
        String account = jwtUtil.getAccountFromToken(token);
        request.setAttribute("userId", userId);
        
        log.info("token验证成功，用户ID：{}, 账号：{}", userId, account);
        return true;
    }
}
